/*
 * Copyright (C) 2008-2011 University of Deusto
 * 
 * All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.
 * 
 * This software consists of contributions made by many individuals, 
 * listed below:
 *
 * Author: Aitor Gómez Goiri <aitor.gomez@deusto.es>
 */

package otso.se.network.sockets.communication.resources;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.restlet.data.Status;
import org.restlet.resource.ResourceException;

import otso.se.network.sockets.communication.OtsopackSocketApplication;
import otso.se.network.sockets.communication.abstraction.IConcernedAboutApplication;
import otso.se.network.sockets.communication.abstraction.IConcernedAboutArguments;
import otso.se.network.sockets.communication.abstraction.ISocketApplication;
import otsopack.commons.IController;
import otsopack.commons.data.impl.SemanticFormatsManager;
import otsopack.full.java.network.communication.representations.SemanticFormatRepresentationFactory;

public class AbstractServerResource implements IConcernedAboutApplication, IConcernedAboutArguments {
	private OtsopackSocketApplication app;
	private Map<String, Object> arguments;
	
	protected final static SemanticFormatsManager semanticFormatsManager = new SemanticFormatsManager();
	protected final static SemanticFormatRepresentationFactory semanticFormatRepresentationFactory = new SemanticFormatRepresentationFactory();
	
	@Override
	public void setArguments(Map<String, Object> arguments) {
		this.arguments = arguments;
	}
	
	@Override
	public void setApplication(ISocketApplication app) {
		this.app = (OtsopackSocketApplication) app;
	}	
	
	protected String getArgument(String argumentName){
		if( !this.arguments.containsKey(argumentName) ) return null;
		
		final String prefname = this.arguments.get(argumentName).toString();
		try {
			return URLDecoder.decode(prefname, "utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Prefix must be an UTF-8 encoded value", e);
		}		
	}
	
	protected IController getController() {
		return getOtsopackApplication().getController();
	}
	
	protected OtsopackSocketApplication getOtsopackApplication(){
		return this.app;
	}	
	
	protected ConcurrentHashMap<String, String> getPrefixesByURI(){
		return getOtsopackApplication().getPrefixesStorage().getPrefixesByURI();
	}
	
	protected ConcurrentHashMap<String, String> getPrefixesByName(){
		return getOtsopackApplication().getPrefixesStorage().getPrefixesByName();
	}
	
	protected String getPrefixByName(String prefixName) {
		return getOtsopackApplication().getPrefixesStorage().getPrefixByName(prefixName);
	}
	
	protected String getPrefixByURI(String prefixUri) {
		return getOtsopackApplication().getPrefixesStorage().getPrefixByURI(prefixUri);
	}
}